<template>
  <a-form :form="form">
    <a-divider>任务设置</a-divider>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="任务名称"
        >
          <a-input
            v-decorator="['taskName', {rules: [{required: true, message: '请输入任务名称!'}]}]"
            placeholder="请输入任务名称" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="定时任务corn"
        >
          <a-input
            v-decorator="['jobCron', {rules: [{required: true, message: '请输入定时任务!'}]}]"
            placeholder="请输入定时任务" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="执行器">
          <a-select
            v-decorator="['executorId', {rules: [{ required: true, message: '请选择执行器!' }]}]"
            placeholder="请选择执行器"
            style="width: 100%">
            <a-select-option
              v-for="(it1) in actuatorList"
              :key="it1.id"
              :value="it1.id">
              {{ it1.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="jvm启动参数"
        >
          <a-input
            v-decorator="['jvmStartParam', {rules: [{required: false, message: '请输入jvm启动参数!'}]}]"
            placeholder="请输入jvm启动参数" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-divider>数据库设置</a-divider>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="选择数据源">
          <a-select
            show-search
            v-decorator="['datasourceId', {rules: [{ required: true, message: '请选择数据源！' }]}]"
            placeholder="请选择数据源"
            style="width: 100%"
            @change="dataSourceChange">
            <a-select-option
              v-for="(item) in dataSourceList"
              :key="item.id"
              :value="item.id">
              {{ item.connectName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          has-feedback
          label="目标数据源">
          <a-select
            show-search
            v-decorator="['targetDatasourceId', {rules: [{ required: true, message: '请选择目标数据源！' }]}]"
            placeholder="请选择目标数据源"
            style="width: 100%"
            @change="targetDataSourceChange">
            <a-select-option
              v-for="(item) in dataSourceList"
              :key="item.id"
              :value="item.id">
              {{ item.connectName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          label="选择源表:">
          <a-select
            show-search
            v-decorator="['tableName', {rules: [{ required: true, message: '请选择源表！' }]}]"
            placeholder="请选择源表"
            style="width: 100%"
            @change="onSelectTable">
            <a-select-option v-for="(it,j) in tables" :key="j" :value="it">
              {{ it }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          label="目标表:">
          <a-select
            show-search
            v-decorator="['targetTableName', {rules: [{ required: true, message: '请选择目标表！' }]}]"
            placeholder="请选择目标表"
            style="width: 100%">
            <a-select-option v-for="(it,j) in targetTables" :key="j" :value="it">
              {{ it }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="24">
      <a-col :span="12">
        <a-form-item
          :labelCol="centerLabelCol"
          :wrapperCol="centerWrapperCol"
          label="选择源表主键:">
          <a-select
            v-decorator="['keycol', {rules: [{ required: true, message: '请选择源表主键！' }]}]"
            placeholder="请选择源表主键"
            style="width: 100%">
            <a-select-option
              v-for="(item) in primaryList"
              :key="item.ColumnName"
              :value="item.ColumnName">
              {{ item.ColumnName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-divider>采集字段设置</a-divider>
    <div style="width: 100%;display: inline-flex;justify-content: space-around">
      <span
        v-for="item in contentTitle"
        :key="item"
        style="font-weight: bold;margin-bottom: 6px">
        {{ item }}
      </span>
    </div>
    <a-form-item style="margin-bottom: 0">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item>
            <a-input
              v-for="(item,index) in collectionContent"
              :key="'field_'+item.uuid"
              placeholder="字段名称"
              @change="(v)=>onCNameChange(v,item,index)"
              :defaultValue="item.columnChname"
              style="margin-left: 12px"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item>
            <template v-for="(item,index) in collectionContent">
              <a-input
                v-if="item.itemType===0"
                :key="'column_'+item.uuid"
                :defaultValue="item.ColumnName"
                :disabled="true"
                placeholder="数据库字段"
                style="margin-left: 12px"></a-input>
              <a-select
                v-else
                :key="'column_'+item.uuid"
                placeholder="请选择字段"
                style="margin-left: 12px"
                @change="(v)=>onSelectColumn(v,index)">
                <a-select-option
                  v-for="(it,j) in selectColumns"
                  :key="'select_'+it.uuid"
                  :value="j">
                  {{ it.ColumnName }}
                </a-select-option>
              </a-select>
            </template>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item>
            <a-input
              v-for="(item) in collectionContent"
              :key="'type_'+item.uuid"
              :defaultValue="item.ColumnTypeName"
              :disabled="true"
              placeholder="字段类型"
              style="margin-left: 12px"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item>
            <div
              v-for="(item,index) in collectionContent"
              :key="'delete_'+item.uuid"
              style="width: 100%;height: 40px;position: relative; display: block;margin: 0 ;padding: 0;text-align: center">
              <a-icon
                style="font-size: 19px;color: #999999;margin:0;padding:0"
                type="delete"
                @click="deleteCollection(index)" />
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form-item>
    <icon-font
      v-if="showAppend"
      style="font-size: 30px;margin-bottom: 16px;margin-top:-12px;color: #1890ff;margin-left: 12px"
      type="icon-roundadd"
      @click="addCollectionContentItem" />
  </a-form>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import {
  datasourceList,
  getAllTables,
  getTableAllColumns
} from '@/api/modular/main/knowl/data_source/dataSourceManager'
import { executorManagementList } from '@/api/modular/main/knowl/executor/executorManagement'
import { addCatchTask } from '@/api/modular/main/knowl/catchtask_config/catchTaskConfigManager'

export default {
  data() {
    return {
      centerLabelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      centerWrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      contentTitle: ['字段名称', '采集字段', '规则类型', '操作'],
      collectionContent: [],
      columns: [],
      form: this.$form.createForm(this),
      dataSourceList: [],
      tables: [],
      targetTables: [],
      selectColumns: [],
      actuatorList: [],
      dataSourceId: undefined,
      datasource: undefined,
      targetDatasource: undefined,
      primaryList: [],
      detail: undefined
    }
  },
  mounted() {
    this.onInit()
  },
  computed: {
    showAppend() {
      if (this.collectionContent.length === 0 && this.columns.length > 0) {
        return true
      }
      return this.collectionContent.length !== this.columns.length
    }
  },
  methods: {
    onInit() {
      this.queryDataSourceList()
      this.queryActuators()
    },
    setDetail(e) {
      this.detail = e
    },
    dispose() {
      this.detail = undefined
      this.form.resetFields()
      this.dataSourceId = undefined
      this.datasource = undefined
      this.targetDatasource = undefined
      this.targetDatasourceId = undefined
      this.dataSourceList = []
      this.tables = []
      this.columns = []
      this.actuatorList = []
      this.selectColumns = []
      this.collectionContent = []
      this.primaryList = []
    },
    onCNameChange(v, item, index) {
      this.collectionContent[index].columnChname = v.target.value
    },
    onSelectColumn(index, parentIndex) {
      const parentItem = this.collectionContent[parentIndex]
      const item = this.selectColumns[index]
      this.selectColumns.splice(index, 1)
      item['itemType'] = 0
      item['columnChname'] = parentItem['columnChname']
      this.collectionContent.splice(parentIndex, 1, item)
    },
    deleteCollection(index) {
      const item = this.collectionContent[index]
      this.collectionContent.splice(index, 1)
      item.columnChname = ''
      this.selectColumns.push(item)
    },
    addCollectionContentItem() {
      this.collectionContent.push({
        'itemType': 1,
        'uuid': uuidv4()
      })
    },
    queryLocalDatasourceId(id) {
      const item = this.dataSourceList.find((it) => id === it.id)
      return item ? item.connectName : undefined
    },
    targetDataSourceChange(id) {
      this.targetDatasource = this.queryLocalDatasourceId(id)
      this.targetDatasourceId = id
      this.targetTables = []
      this.form.setFieldsValue(
        {
          targetTableName: undefined
        }
      )
      this.$emit('loading')
      getAllTables({
        'id': id
      })
        .then((res) => {
          this.targetTables = res.data
          if (this.detail) {
            this.form.setFieldsValue(
              {
                targetTableName: this.detail['targetTableName']
              }
            )
          }
        })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$emit('dismiss')
      })
    },
    dataSourceChange(id) {
      this.dataSourceId = id
      this.datasource = this.queryLocalDatasourceId(id)
      this.tables = []
      this.form.setFieldsValue(
        {
          tableName: undefined
        }
      )
      this.collectionContent = []
      this.columns = []
      this.clearColumns()
      this.$emit('loading')
      getAllTables({
        'id': id
      })
        .then((res) => {
          this.tables = res.data
          if (this.detail) {
            this.form.setFieldsValue(
              {
                tableName: this.detail['tableName']
              }
            )
            this.onSelectTable(this.detail['tableName'])
          }
        })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$emit('dismiss')
      })
    },

    onSelectTable(value) {
      this.collectionContent = []
      this.columns = []
      this.clearColumns()
      this.$emit('loading')
      getTableAllColumns({
        'id': this.dataSourceId,
        'tableName': value
      }).then((res) => {
        res.data.forEach((it) => {
          it['uuid'] = uuidv4()
          it['itemType'] = 0
          it['columnChname'] = ''
        })
        this.columns = res.data.slice()
        this.primaryList = res.data.slice().filter((it) => it.IsPrmKey === '1')
        if (this.detail) {
          const keycol = this.detail['keycol']
          this.form.setFieldsValue({
            'keycol': keycol
          })
          const catchColumns = this.detail['catchColumns']
          const newColumns = []
          catchColumns.forEach((i) => {
            const columnInfo = res.data.find((it) => i.columnName === it.ColumnName)
            if (columnInfo) {
              const newColumn = Object.assign(columnInfo)
              newColumn['columnChname'] = i['columnChname']
              newColumns.push(newColumn)
            }
          })
          res.data.forEach((i) => {
            const find = newColumns.find((col) => col.ColumnName === i.ColumnName)
            if (!find) {
              this.selectColumns.push(i)
            }
          })
          this.collectionContent = newColumns
        } else {
          this.collectionContent = res.data
        }
      })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$emit('dismiss')
      })
    },
    queryActuators() {
      executorManagementList({}).then((res) => {
        if (res.code === 200) {
          this.actuatorList = res.content
          if (this.detail) {
            const id = this.detail['executorId']
            this.form.setFieldsValue({
              'executorId': parseInt(id)
            })
          }
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    queryDataSourceList() {
      this.$emit('loading')
      datasourceList({}).then((res) => {
        this.dataSourceList = res.data
        if (this.detail) {
          const datasourceId = this.detail['datasourceId']
          const targetDatasourceId = this.detail['targetDatasourceId']
          this.form.setFieldsValue({
            'datasourceId': datasourceId,
            'targetDatasourceId': targetDatasourceId
          })
          this.dataSourceChange(datasourceId)
          this.targetDataSourceChange(targetDatasourceId)
        }
      })
        .catch((e) => {
          console.log(e)
        }).finally(() => {
        this.$emit('dismiss')
      })
    },
    clearColumns() {
      this.primaryList = []
      this.form.setFieldsValue(
        {
          keycol: undefined
        }
      )
    },
    // 还原数据
    edit() {
      const entity = this.detail
      this.form.setFieldsValue({
        'jobCron': entity['jobCron'],
        'taskName': entity['taskName'],
        'jvmStartParam': entity['jvmStartParam']
      })
      this.onInit()
    },
    saveOrUpdate(id) {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          if (this.collectionContent.length <= 0) {
            this.$message.error('采集字段不能为空!')
          } else {
            for (const key in values) {
              if (typeof (values[key]) === 'object') {
                values[key] = JSON.stringify(values[key])
              }
            }
          }
          let fieldNameEmpty = false
          const count = this.collectionContent.length
          for (let i = 0; i < count; i++) {
            const it = this.collectionContent[i]
            if (!it['columnChname']) {
              fieldNameEmpty = true
              break
            }
          }
          if (fieldNameEmpty) {
            this.$message.error('采集字段不能为空!')
            return
          }
          this.insertValue(values, id)
        }
      })
    },

    insertValue(values, id) {
      const catchColumns = []
      this.collectionContent.forEach((it) => {
        const item = it
        item['columnName'] = it['ColumnName']
        item['columnType'] = it['ColumnTypeName']
        catchColumns.push(item)
      })
      values['catchColumns'] = catchColumns
      values['datasource'] = this.datasource
      values['dataSourceId'] = this.dataSourceId
      values['targetDatasource'] = this.targetDatasource
      values['targetDatasourceId'] = this.targetDatasourceId
      const executor = this.actuatorList.find((it) => it.id === values['executorId'])
      values['executor'] = executor ? executor.title : undefined
      values['step'] = 1
      values['id'] = id
      this.$emit('loading')
      addCatchTask(values, id)
        .then((res) => {
          if (res.success) {
            const responseValue = res['data']
            this.$emit('parentNext', responseValue)
          } else {
            this.$message.error(res['message'])
          }
        })
        .catch((e) => {
          console.log(e)
        })
        .finally(() => {
          this.$emit('dismiss')
        })
    }
  }
}
</script>

<style scoped>

</style>
